import axios from "axios";
import {
	Message,
	Loading
} from "element-ui";
// import Cookies from "js-cookie";
import {
	generateUUID
} from "./index.js";
// import store from '../store'
// const sha1 = require('sha1')
export const apiClassify = {
	ddcPort: "ddc-port"
};

//测试：接口全名：https://api.dingdangcode.com/ddc-port/play/getDraftList?pageNum=1&pageSize=10&keywords=&type=2

// create an axios service
const service = axios.create({
	baseURL: "http://localhost:8081", //process.env.VUE_APP_BASE_URL, // 根据不同环境，配置BASE_URL测试
	timeout: 15 * 1000 //30 * 1000 // request timeout
});

//创建一个全局的loading
let loadingInstance;

/*请求合并只出现一次loading*/
let needLoadingRequestCount = 0;

function showFullScreenLoading() {
	if (needLoadingRequestCount === 0) {
		// startLoading();
	}
	needLoadingRequestCount++;
}

function tryHideFullScreenLoading() {
	if (needLoadingRequestCount <= 0) return;
	needLoadingRequestCount--;
	if (needLoadingRequestCount === 0) {
		setTimeout(tryCloseLoading, 300); /*300ms 间隔内的 loading 合并为一次*/
	}
}
const tryCloseLoading = () => {
	if (needLoadingRequestCount === 0) {
		// endLoading();
	}
};
/*loading加载*/
function startLoading() {
	loadingInstance = Loading.service({
		background: "rgba(0, 0, 0, 0.7)"
	});
}

// function endLoading() {
//   loadingInstance.close();
// }

let count = 0;

function showMsg(errorText) {
	return Message({
		message: errorText,
		type: "error",
		duration: 3 * 1000,
		onClose: function() {
			count = 0;
		}
	});
}

function msg(errorText) {
	if (count === 0) {
		showMsg(errorText);
	}
	count++;
}

const editBasUrl = function(config) {
	// 签名算法
	let _headers = [];
	let signToken = "766a6afe879b44bd9c5c7518746bd0e4";
	let timestamp = Date.now().toString();
	let nonce = generateUUID();
	_headers.push(signToken, timestamp, nonce);
	// let shaStr = sha1(_headers.sort().join(''))//测试
	// 接口请求的所有配置，都在这个config对象中，他的类型是AxiosRequestConfig，你可以看到他有哪些字段
	// 如果你要修改接口请求配置，需要修改 axios.defaults 上的字段值
	config.headers.timestamp = timestamp;
	config.headers.nonce = nonce;
	config.headers.signature = "7550d6360d0e89173669c77566510de4dfb29b60"; //shaStr//测试

	config.baseURL = "http://localhost:8081"; //测试process.env.VUE_APP_BASE_URL;
};

// request interceptor
service.interceptors.request.use(
	config => {
		// Do something before request is sent
		if (config.url.indexOf("aiDetect/getAiChatResponse") === -1) {
			showFullScreenLoading();
		}
		if (config.url !== "http://10.28.63.127:9006/linux") {
			editBasUrl(config);
			config.headers["Content-Type"] = "application/x-www-form-urlencoded";
			let token =
				'bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiZmlsZS1idWNrZXQiLCJnYXRld2F5IiwiZ3VuLWRldGFpbHMiXSwidXNlcl9uYW1lIjoicGFuZGEiLCJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNjc3MjQ3NTk3LCJhdXRob3JpdGllcyI6WyJST0xFX0FETUlOIl0sImp0aSI6IjQ4N2UyOWQ5LTkxNWItNDBlMS04MTg3LWVmMTEwMjIwOWFjYiIsImNsaWVudF9pZCI6ImNucGNNYW5hZ2VyIn0.Iu0RrCErCRhbkWuzVHbqN5DZcgk0pv61PLKXHkSPnWL4wv2EMP9lOaRmBErU2_3ax-R9YG5IIMNJEkysdS87TEKAnNVG1q5o2QLPzaMFVnBNmoQ5w085H_bP28K6yDxLnrU2gJZUyuy5uCwzYAqTXRd2RNqtILzkbe84WqsTt5yfuGwvAEbyvPZ6-MrKqAE4r--1iIrc9hTdUpYymmiaRLLp2fZ2Qqufqu-rbQo7eE2tb4da1hVLWbHMjbcrJTaE7q4Aq7kKnw68Mt5lpXLZq1aDL4Ebn4q8AccgyU0LXtBxvswrTiNw8iOemKQniKdf6XsA0pNCHneEhSkduYWV-A';
			config.headers.Authorization = token; //测试 config.headers.common['token'] = Cookies.get('token') Cookies.get("token"); //PLAY_TOKEN
			// console.log(2222, config);
			return config;
		} else if (config.url === "http://10.28.63.127:9006/linux") {
			// console.log(config.url);
			editBasUrl(config);
			config.headers["Content-Type"] = "application/json;charset=UTF-8";
			let token =
				'bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiZmlsZS1idWNrZXQiLCJnYXRld2F5IiwiZ3VuLWRldGFpbHMiXSwidXNlcl9uYW1lIjoicGFuZGEiLCJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNjc3MjQ3NTk3LCJhdXRob3JpdGllcyI6WyJST0xFX0FETUlOIl0sImp0aSI6IjQ4N2UyOWQ5LTkxNWItNDBlMS04MTg3LWVmMTEwMjIwOWFjYiIsImNsaWVudF9pZCI6ImNucGNNYW5hZ2VyIn0.Iu0RrCErCRhbkWuzVHbqN5DZcgk0pv61PLKXHkSPnWL4wv2EMP9lOaRmBErU2_3ax-R9YG5IIMNJEkysdS87TEKAnNVG1q5o2QLPzaMFVnBNmoQ5w085H_bP28K6yDxLnrU2gJZUyuy5uCwzYAqTXRd2RNqtILzkbe84WqsTt5yfuGwvAEbyvPZ6-MrKqAE4r--1iIrc9hTdUpYymmiaRLLp2fZ2Qqufqu-rbQo7eE2tb4da1hVLWbHMjbcrJTaE7q4Aq7kKnw68Mt5lpXLZq1aDL4Ebn4q8AccgyU0LXtBxvswrTiNw8iOemKQniKdf6XsA0pNCHneEhSkduYWV-A';
			config.headers.Authorization = token; //测试 config.headers.common['token'] = Cookies.get('token') Cookies.get("token"); //PLAY_TOKEN
			// console.log(2222, config);
			return config;
		}

	},
	error => {
		msg("网络繁忙，请稍后再试");
		tryHideFullScreenLoading();
		Promise.reject(error);
	}
);

// response interceptor
service.interceptors.response.use(
	response => {
		const res = response.data;
		// console.log(response);
		tryHideFullScreenLoading();
		if (res.code != 0) {
			// loadingInstance.close();
			if (res.code == 107) {
				// 需 return response 否则 获取到异常数据 临时解决方案
				if (location.pathname === "/404") {
					return response;
				} else {
					Message({
						message: res.msg,
						type: "error",
						duration: 3 * 1000
					});
					// store.dispatch('FedLogOut').then(() => {
					//   location.reload() // 为了重新实例化vue-router对象 避免bug
					// })
				}
			} else if (res.code == 14) {
				Message({
					message: res.msg,
					type: "error",
					duration: 3 * 1000
				});
			} else if (res.code == 35) {
				Message({
					message: "账号已在另一地点登录，你的账号被迫下线。若非本人操作，建议重新登录账号并修改密码。",
					type: "error",
					duration: 3 * 1000
				});
				// store.commit('userInfo/REMOVE_TOKEN')
			} else {
				return response;
			}
			return Promise.reject("error");
		} else {
			return response;
		}
	},
	error => {
		if (error.response) {
			switch (error.response.status) {
				case 400:
					error.message = "错误请求";
					msg("错误请求");
					break;
				case 401:
					error.message = "未授权，请重新登录";
					msg("未授权，请重新登录");
					break;
				case 403:
					error.message = "拒绝访问";
					msg("拒绝访问");
					break;
				case 404:
					error.message = "请求错误,未找到该资源";
					msg("请求错误,未找到该资源");
					break;
				case 405:
					error.message = "请求方法未允许";
					msg("请求方法未允许");
					break;
				case 408:
					error.message = "请求超时";
					msg("请求超时");
					break;
				case 500:
					error.message = "服务器端出错";
					msg("服务器端出错");
					break;
				case 501:
					error.message = "网络未实现";
					msg("网络未实现");
					break;
				case 502:
					error.message = "网络错误";
					msg("网络错误");
					break;
				case 503:
					error.message = "服务不可用";
					msg("服务不可用");
					break;
				case 504:
					error.message = "网络超时";
					msg("网络超时");
					break;
				case 505:
					error.message = "http版本不支持该请求";
					msg("http版本不支持该请求");
					break;
				default:
					error.message = `连接错误${error.response.status}`;
					msg(`'连接错误'${error.response.status}`);
			}
		} else {
			error.message = `连接服务器失败`;
			msg(`连接服务器失败`);
		}
		tryHideFullScreenLoading();
		// console.log("222222:" + error); // for debug
		return Promise.reject(error);
	}
);

export default service;
